package com.kgc.scd.Controller;

import com.kgc.scd.Constant.WechatPayConstant;
import com.kgc.scd.service.WechatPayService;
import com.kgc.scd.util.WechatPayXmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Created On : 2022/11/3.
 * <p>
 * Author : zhukang
 * <p>
 * Description: 微信支付接口对接测试入口
 */
@Slf4j
@RestController
public class WechatPayController {

    @Autowired
    private WechatPayService wechatPayService;

    /**
     * @author : zhukang
     * @date   : 2022/11/3
     * @param  : []
     * @return : com.kgc.scd.util.RequestResult<java.util.Map<java.lang.String,java.lang.String>>
     * @description : 请求微信统一下单接口，下预支付订单，返回支付链接
     */
    @PostMapping("/unifyOrder")
    public Map<String, Object> wechatPayUnifyOrder(Integer orderPrice,@RequestBody Map<String,String> msgMap) throws Exception {


        log.info("server:"+orderPrice);
        log.info("server:"+msgMap);
        // 调用业务接口，生成请求微信支付接口，统一下的完整参数，xml格式的，微信支付接口要求
        String unifyOrderXmlParams = wechatPayService.generateWxpayUnifyOrderXmlParams(msgMap, orderPrice);

        log.info("------ 1 请求微信支付统一下单接口参数：{} ------", unifyOrderXmlParams);

        // 调用业务接口，请求微信支付统一下单接口，获取下单结果
        Map<String, String> unifyOrderMapResult = wechatPayService.getWechatPayUnifyOrderResult(unifyOrderXmlParams);

        log.info("------ 2 请求微信支付统一下单接口返回：{} ------", unifyOrderMapResult);

        // 定义当前接口返回的map集合
        Map<String, Object> resultMap = new HashMap<>();

        // 解析微信支付统一下单结果，如果下单成功，获取用户进行扫码支付的链接，返回给前端，生成二维码，扫码支付
        if (WechatPayConstant.WECHAT_PAY_RESULT_SUCCESS.equals(unifyOrderMapResult.get("return_code"))
                && WechatPayConstant.WECHAT_PAY_RESULT_SUCCESS.equals(unifyOrderMapResult.get("result_code"))){
            // 微信支付统一下单成功，省略签名校验

            // 获取成功的结果
            // 交易类型
            resultMap.put("trade_type", unifyOrderMapResult.get("trade_type"));

            // 预支付交易会话标识
            resultMap.put("prepay_id", unifyOrderMapResult.get("prepay_id"));

            // 二维码链接
            resultMap.put("code_url", unifyOrderMapResult.get("code_url"));

            // 返回统一下预支付单成功
            return resultMap;
        }

        // 统一下预支付单失败
        resultMap.put("errCode", unifyOrderMapResult.get("return_code"));
        resultMap.put("errMsg", unifyOrderMapResult.get("return_msg"));
        return resultMap;
    }

    /**
     * @author : zhukang
     * @date   : 2022/11/3
     * @param  : [request, response]
     * @return : void
     * @description : 接收用户支付成功后，微信异步回调支付结果
     */
    @RequestMapping("/wxpay/notifyresult")
    public void receiveWechatPayNotifyResult(HttpServletRequest request, HttpServletResponse response){

        // 支付完成后，微信会把相关支付结果及用户信息通过数据流的形式发送给商户，商户需要接收处理，并按文档规范返回应答
        try (InputStream inputStream = request.getInputStream()){

            // 解析回调支付结果数据流
            BufferedReader bfr = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

            // 定义可变字符串对象，保存返回的xml格式支付结果
            StringBuilder wxpayNotifyXmlResult = new StringBuilder();

            // 逐行解析
            String readLine = null;
            while ((readLine = bfr.readLine()) != null){
                wxpayNotifyXmlResult.append(readLine);
            }

            log.info("------ 3 微信支付结果异步回调内容：{} ------", wxpayNotifyXmlResult);

            // 调用业务接口，解析异步回调的支付结果，并获取通知微信官方的响应结果
            String respWechatXmlResult = wechatPayService.getReturnWechatXmlResult(wxpayNotifyXmlResult.toString());


            // 同步给微信官方响应结果
            PrintWriter out = response.getWriter();
            out.write(respWechatXmlResult);
            out.flush();
            out.close();

            log.info("------ 4 微信支付结果异步回调处理后，响应结果：{} ------", respWechatXmlResult);

        } catch (Exception e){
            log.info("------ 微信支付结果异步回调处理异常，异常信息：{} ------", e.getMessage());
        }
    }
}
